<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import {
  getDishListAPI,
  getDishDetailAPI,
  addDishAPI,
  updateDishAPI,
  deleteDishAPI,
  getMerchantSelectAPI,
  getIngredientSelectAPI,
  addDishIngredientsAPI,
  updateDishFlavorAPI
} from '@/api/dish'
import { uploadFileAPI } from '@/api/upload'

// 搜索和筛选条件
const searchText = ref('')
const categoryId = ref('')
const merchant = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(8)
const totalCount = ref(0)

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 抽屉相关
const drawerVisible = ref(false)
const drawerTitle = ref('添加菜品')
const currentDishId = ref(null)
const isViewMode = ref(false)

// 详情弹窗相关
const detailDialogVisible = ref(false)
const detailData = ref({})

// 食材和口味相关弹窗
const ingredientDialogVisible = ref(false)
const flavorDialogVisible = ref(false)

// 评分弹窗相关
const ratingDialogVisible = ref(false)
const currentRatingDishId = ref(null)

// 表单数据
const formData = reactive({
  id: '',
  merchantId: '',
  dishName: '',
  dishCategoryId: [],
  calorie: 0,
  image: '',
  price: 0,
  description: ''
})

// 分类数据
const categories = ref([
  { id: 1, name: '早饭' },
  { id: 2, name: '午饭' },
  { id: 3, name: '晚饭' },
  { id: 4, name: '米饭' },
  { id: 5, name: '饮品' }
])

// 商家数据（从接口获取）
const merchants = ref([])
const merchantLoading = ref(false)
const merchantSearchText = ref('')
const topMerchantSearchText = ref('')

// 食材相关 - 修复多选问题，使用ID数组存储选中状态
const ingredients = ref([])
const selectedIngredientIds = ref([]) // 存储选中的食材ID
const selectedIngredients = ref([]) // 存储选中的食材对象，用于显示
const ingredientSearchText = ref('')
const ingredientLoading = ref(false)

// 口味相关
const flavorOptions = ref([
  { name: '酸', id: 'sour' },
  { name: '甜', id: 'sweet' },
  { name: '苦', id: 'bitter' },
  { name: '辣', id: 'spicy' },
  { name: '咸', id: 'salty' },
  { name: '香', id: 'fragrant' },
  { name: '麻', id: 'numbing' }
])
const selectedFlavors = ref([]) // 存储选中的口味ID

// 监听食材ID变化，同步更新食材对象数组
watch(selectedIngredientIds, (newIds) => {
  // 只在添加菜品时处理
  if (!currentDishId.value) {
    selectedIngredients.value = ingredients.value.filter((ing) =>
      newIds.includes(ing.id)
    )
  }
})

// 获取菜品列表
const fetchDishList = async () => {
  try {
    loading.value = true
    const res = await getDishListAPI(
      currentPage.value,
      pageSize.value,
      searchText.value,
      categoryId.value,
      merchant.value
    )

    if (res.data.code === 1 && res.data.data) {
      tableData.value = res.data.data.records || []
      totalCount.value = res.data.data.total || 0
    } else {
      ElMessage.warning('获取菜品列表失败')
      tableData.value = []
      totalCount.value = 0
    }
  } catch (error) {
    ElMessage.error('获取菜品列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取商家列表
const fetchMerchants = async (search = '') => {
  try {
    merchantLoading.value = true
    const res = await getMerchantSelectAPI(search)

    if (res.data.code === 1 && res.data.data) {
      merchants.value = res.data.data.records.map((merchant) => ({
        id: merchant.id,
        name: merchant.merchantName || `商家${merchant.id}`
      }))
    } else {
      ElMessage.warning('获取商家列表失败')
      merchants.value = []
    }
  } catch (error) {
    ElMessage.error('获取商家列表失败')
    console.error(error)
  } finally {
    merchantLoading.value = false
  }
}

// 获取食材列表
const fetchIngredients = async (search = '') => {
  try {
    ingredientLoading.value = true
    const res = await getIngredientSelectAPI(search)

    if (res.data.code === 1 && res.data.data) {
      ingredients.value = res.data.data

      // 如果是添加状态且已有选中的ID，同步更新选中的食材对象
      if (!currentDishId.value && selectedIngredientIds.value.length > 0) {
        selectedIngredients.value = ingredients.value.filter((ing) =>
          selectedIngredientIds.value.includes(ing.id)
        )
      }
    } else {
      ElMessage.warning('获取食材列表失败')
      ingredients.value = []
    }
  } catch (error) {
    ElMessage.error('获取食材列表失败')
    console.error(error)
  } finally {
    ingredientLoading.value = false
  }
}

// 初始加载
onMounted(() => {
  fetchDishList()
  fetchMerchants()
  fetchIngredients() // 初始加载食材列表，供新增菜品使用
})

// 监听商家搜索文本变化（抽屉内）
watch(merchantSearchText, (newVal) => {
  const timer = setTimeout(() => {
    fetchMerchants(newVal)
  }, 300)
  return () => clearTimeout(timer)
})

// 监听顶部商家搜索文本变化
watch(topMerchantSearchText, (newVal) => {
  const timer = setTimeout(() => {
    fetchMerchants(newVal)
  }, 300)
  return () => clearTimeout(timer)
})

// 监听食材搜索文本变化
watch(ingredientSearchText, (newVal) => {
  const timer = setTimeout(() => {
    fetchIngredients(newVal)
  }, 300)
  return () => clearTimeout(timer)
})

// 搜索和筛选
const handleSearch = () => {
  currentPage.value = 1
  fetchDishList()
}

// 重置筛选条件
const handleReset = () => {
  searchText.value = ''
  merchant.value = ''
  categoryId.value = ''
  topMerchantSearchText.value = ''
  currentPage.value = 1
  fetchDishList()
  fetchMerchants()
}

// 查看菜品详情
const handleView = async (row) => {
  const loadingInstance = ElLoading.service({ text: '加载中...' })
  try {
    const response = await getDishDetailAPI(row.id)
    if (response.data.code === 1 && response.data.data) {
      detailData.value = response.data.data

      // 处理分类ID
      if (detailData.value.dishCategoryId) {
        detailData.value.categoryIds = detailData.value.dishCategoryId
          .toString()
          .split('')
          .map((id) => parseInt(id))
      }

      // 处理口味数据 - 转换为勾选状态
      if (detailData.value.flavor && detailData.value.flavor.length) {
        selectedFlavors.value = flavorOptions.value
          .filter((flavor) => detailData.value.flavor.includes(flavor.name))
          .map((flavor) => flavor.id)
      } else {
        selectedFlavors.value = []
      }

      // 处理食材数据
      if (detailData.value.ingredients) {
        selectedIngredients.value = [...detailData.value.ingredients]
      }

      detailDialogVisible.value = true
    } else {
      ElMessage.warning('获取菜品详情失败')
    }
  } catch (error) {
    ElMessage.error('获取菜品详情失败')
    console.error(error)
  } finally {
    loadingInstance.close()
  }
}

// 打开添加抽屉
const handleAdd = () => {
  drawerTitle.value = '添加菜品'
  currentDishId.value = null
  isViewMode.value = false

  // 重置表单
  Object.keys(formData).forEach((key) => {
    if (key === 'dishCategoryId') {
      formData[key] = []
    } else if (key === 'price' || key === 'calorie') {
      formData[key] = 0
    } else {
      formData[key] = ''
    }
  })

  // 重置口味选择
  selectedFlavors.value = []

  // 重置食材选择 - 同时清空ID和对象数组
  selectedIngredientIds.value = []
  selectedIngredients.value = []

  // 加载食材列表
  fetchIngredients()

  drawerVisible.value = true
}

// 打开编辑抽屉
const handleEdit = async (row) => {
  const loadingInstance = ElLoading.service({ text: '加载中...' })
  try {
    const response = await getDishDetailAPI(row.id)
    if (response.data.code === 1 && response.data.data) {
      const dish = response.data.data
      drawerTitle.value = '编辑菜品'
      currentDishId.value = dish.id
      isViewMode.value = false

      // 填充表单数据
      formData.id = dish.id
      formData.merchantId = dish.merchantId
      formData.dishName = dish.dishName
      formData.calorie = dish.calorie || 0
      formData.image = dish.image || ''
      formData.price = dish.price || 0
      formData.description = dish.description || ''

      // 处理分类ID
      if (dish.dishCategoryId) {
        formData.dishCategoryId = dish.dishCategoryId
          .toString()
          .split('')
          .map((id) => parseInt(id))
      } else {
        formData.dishCategoryId = []
      }

      // 处理口味数据 - 转换为勾选状态
      if (dish.flavor && dish.flavor.length) {
        selectedFlavors.value = flavorOptions.value
          .filter((flavor) => dish.flavor.includes(flavor.name))
          .map((flavor) => flavor.id)
      } else {
        selectedFlavors.value = []
      }

      // 处理食材数据
      if (dish.ingredients) {
        selectedIngredients.value = [...dish.ingredients]
        selectedIngredientIds.value = dish.ingredients.map((ing) => ing.id)
      } else {
        selectedIngredients.value = []
        selectedIngredientIds.value = []
      }

      drawerVisible.value = true
    } else {
      ElMessage.warning('获取菜品详情失败')
    }
  } catch (error) {
    ElMessage.error('获取菜品详情失败')
    console.error(error)
  } finally {
    loadingInstance.close()
  }
}

// 提交表单（添加或编辑）
const handleSubmit = async () => {
  // 验证必填项
  if (!formData.merchantId) {
    ElMessage.warning('请选择所属商家')
    return
  }

  if (!formData.dishName) {
    ElMessage.warning('请输入菜品名称')
    return
  }

  if (!formData.dishCategoryId || formData.dishCategoryId.length === 0) {
    ElMessage.warning('请选择菜品分类')
    return
  }

  if (formData.price <= 0) {
    ElMessage.warning('请输入有效的价格')
    return
  }

  try {
    // 处理分类ID
    const submitData = {
      ...formData,
      dishCategoryId: formData.dishCategoryId.sort((a, b) => a - b).join('')
    }

    // 对于添加菜品，同时包含食材和口味信息
    if (!currentDishId.value) {
      // 处理口味信息
      if (selectedFlavors.value.length > 0) {
        submitData.flavors = flavorOptions.value
          .filter((flavor) => selectedFlavors.value.includes(flavor.id))
          .map((flavor) => flavor.name)
      }

      // 处理食材信息 - 使用选中的ID数组
      if (selectedIngredientIds.value.length > 0) {
        submitData.ingredientIds = [...selectedIngredientIds.value]
      }

      // 添加菜品（一次性提交所有信息）
      const res = await addDishAPI(submitData)
      currentDishId.value = res.data.data.id
      ElMessage.success('菜品添加成功')
    } else {
      // 编辑菜品（保持原有逻辑）
      await updateDishAPI(submitData)
      ElMessage.success('菜品更新成功')
    }

    drawerVisible.value = false
    merchantSearchText.value = ''
    fetchDishList()
  } catch (error) {
    ElMessage.error(currentDishId.value ? '更新菜品失败' : '添加菜品失败')
    console.error(error)
  }
}

// 其他方法保持不变...
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜品 "${row.dishName}" 吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteDishAPI(row.id)
    ElMessage.success('删除成功')
    fetchDishList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchDishList()
}

const handleUpload = async (uploadFile) => {
  try {
    const uploadFormData = new FormData()
    uploadFormData.append('file', uploadFile.file)

    const response = await uploadFileAPI(uploadFormData)
    if (response.data && response.data.code === 1 && response.data.data) {
      formData.image = response.data.data
      ElMessage.success('图片上传成功')
      return true
    } else {
      ElMessage.error('上传失败，未返回图片地址')
      return false
    }
  } catch (error) {
    ElMessage.error('图片上传失败')
    console.error('上传错误:', error)
    return false
  }
}

const openIngredientDialog = () => {
  if (!currentDishId.value && !formData.dishName) {
    ElMessage.warning('请先填写菜品基本信息')
    return
  }
  fetchIngredients()
  ingredientDialogVisible.value = true
}

const toggleIngredient = (ingredient) => {
  const index = selectedIngredients.value.findIndex(
    (ing) => ing.id === ingredient.id
  )

  if (index > -1) {
    selectedIngredients.value.splice(index, 1)
    selectedIngredientIds.value = selectedIngredientIds.value.filter(
      (id) => id !== ingredient.id
    )
  } else {
    selectedIngredients.value.push(ingredient)
    selectedIngredientIds.value.push(ingredient.id)
  }
}

const saveIngredients = async () => {
  if (!currentDishId.value) {
    ElMessage.warning('请先保存菜品基本信息')
    return
  }

  try {
    await addDishIngredientsAPI({
      dishId: currentDishId.value,
      ingredientIds: selectedIngredients.value.map((ing) => ing.id)
    })
    ElMessage.success('食材信息保存成功')
    ingredientDialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存食材信息失败')
    console.error(error)
  }
}

const openFlavorDialog = () => {
  flavorDialogVisible.value = true
}

const saveFlavors = async () => {
  if (!currentDishId.value) {
    ElMessage.warning('请先保存菜品基本信息')
    return
  }

  if (selectedFlavors.value.length === 0) {
    ElMessage.warning('请至少选择一种口味')
    return
  }

  try {
    const flavorNames = flavorOptions.value
      .filter((flavor) => selectedFlavors.value.includes(flavor.id))
      .map((flavor) => flavor.name)

    await updateDishFlavorAPI(currentDishId.value, flavorNames)
    ElMessage.success('口味信息保存成功')
    flavorDialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存口味信息失败')
    console.error(error)
  }
}

const formatCategory = (categoryId) => {
  if (!categoryId) return ''

  const ids = categoryId
    .toString()
    .split('')
    .map((id) => parseInt(id))
  return ids
    .map((id) => {
      const category = categories.value.find((cat) => cat.id === id)
      return category ? category.name : ''
    })
    .filter((name) => name)
    .join('、')
}

const getSelectedMerchantName = () => {
  if (!formData.merchantId) return ''
  const merchant = merchants.value.find((m) => m.id === formData.merchantId)
  return merchant ? merchant.name : ''
}

const handleDrawerClose = () => {
  drawerVisible.value = false
  merchantSearchText.value = ''
}

const openRatingList = (dishId) => {
  currentRatingDishId.value = dishId
  ratingDialogVisible.value = true
}
</script>

<template>
  <div class="dish-management">
    <div class="page-header">
      <h1>菜品管理</h1>
      <div class="header-actions">
        <!-- 分类筛选下拉框 -->
        <el-select
          v-model="categoryId"
          placeholder="选择分类"
          style="width: 150px; margin-right: 12px"
          clearable
        >
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>

        <!-- 商家筛选下拉框 -->
        <el-select
          v-model="merchant"
          placeholder="选择商家"
          style="width: 200px; margin-right: 12px"
          clearable
        >
          <el-input
            v-model="topMerchantSearchText"
            placeholder="搜索商家"
            style="margin-bottom: 8px"
          />
          <el-option
            v-for="item in merchants"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>

        <el-input
          v-model="searchText"
          placeholder="搜索菜品名称"
          style="width: 250px; margin-right: 12px"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleSearch">筛选</el-button>
        <el-button @click="handleReset" style="margin-left: 12px"
          >重置</el-button
        >
        <el-button type="primary" @click="handleAdd" style="margin-left: 12px"
          >添加菜品</el-button
        >
      </div>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
      empty-text="暂无菜品数据"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="菜品图片" width="100">
        <template #default="scope">
          <el-image
            :src="scope.row.image"
            style="width: 60px; height: 60px"
            fit="cover"
            :alt="scope.row.dishName"
          />
        </template>
      </el-table-column>
      <el-table-column prop="dishName" label="菜品名称" />
      <el-table-column label="所属商家">
        <template #default="scope">
          {{ scope.row.merchant || '未知商家' }}
        </template>
      </el-table-column>
      <el-table-column label="分类" width="180">
        <template #default="scope">
          {{ formatCategory(scope.row.dishCategoryId) }}
        </template>
      </el-table-column>
      <el-table-column
        label="价格"
        :formatter="(row) => `￥${row.price.toFixed(1)}`"
      />
      <el-table-column label="热量" prop="calorie" />
      <el-table-column label="评分">
        <template #default="scope">
          <span class="clickable-rating" @click="openRatingList(scope.row.id)">
            {{ scope.row.dishRating.toFixed(2) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleView(row)"
            >查看</el-button
          >
          <el-button size="small" type="warning" @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button size="small" type="danger" @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="totalCount"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑抽屉 -->
    <el-drawer
      :title="drawerTitle"
      v-model="drawerVisible"
      direction="rtl"
      size="50%"
      @close="handleDrawerClose"
    >
      <el-form
        :model="formData"
        label-width="120px"
        style="margin-top: 20px"
        :disabled="isViewMode"
      >
        <el-form-item label="所属商家" prop="merchantId" required>
          <el-select
            v-model="formData.merchantId"
            placeholder="请选择商家"
            clearable
          >
            <el-input
              v-model="merchantSearchText"
              placeholder="搜索商家"
              style="margin-bottom: 8px"
            />
            <el-option
              v-for="item in merchants"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <div v-if="formData.merchantId" class="selected-merchant">
            当前选中: {{ getSelectedMerchantName() }}
          </div>
        </el-form-item>

        <el-form-item label="所属分类" prop="dishCategoryId" required>
          <el-select
            v-model="formData.dishCategoryId"
            placeholder="请选择分类（可多选）"
            multiple
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
          <div class="form-hint">
            提示：按住Ctrl键可多选，如早午餐可同时选择早饭和午饭
          </div>
        </el-form-item>

        <el-form-item label="菜品名称" prop="dishName" required>
          <el-input v-model="formData.dishName" placeholder="请输入菜品名称" />
        </el-form-item>

        <el-form-item label="价格(元)" prop="price" required>
          <el-input-number
            v-model="formData.price"
            :min="0.01"
            :step="0.01"
            placeholder="请输入价格"
          />
        </el-form-item>

        <el-form-item label="热量(卡路里)" prop="calorie">
          <el-input-number
            v-model="formData.calorie"
            :min="0"
            placeholder="请输入热量"
          />
        </el-form-item>

        <el-form-item label="菜品图片" prop="image">
          <el-upload
            :http-request="handleUpload"
            list-type="picture"
            :disabled="isViewMode"
            :headers="{ 'Content-Type': undefined }"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
          <el-image
            v-if="formData.image"
            :src="formData.image"
            style="width: 100px; height: 100px; margin-top: 10px"
            fit="cover"
            :alt="formData.dishName"
          />
        </el-form-item>

        <el-form-item label="菜品描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入菜品描述"
          />
        </el-form-item>

        <!-- 新增菜品时直接显示口味选择 -->
        <el-form-item label="菜品口味" v-if="!currentDishId">
          <el-checkbox-group v-model="selectedFlavors">
            <el-checkbox
              v-for="flavor in flavorOptions"
              :key="flavor.id"
              :label="flavor.id"
              style="margin-right: 15px; margin-bottom: 10px"
            >
              {{ flavor.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 新增菜品时直接显示食材选择 -->
        <el-form-item label="菜品食材" v-if="!currentDishId">
          <el-input
            v-model="ingredientSearchText"
            placeholder="搜索食材"
            style="margin-bottom: 8px"
            clearable
          />
          <!-- 修改为使用ID数组进行绑定 -->
          <el-select
            v-model="selectedIngredientIds"
            placeholder="请选择食材（可多选）"
            multiple
            filterable
          >
            <el-option
              v-for="ingredient in ingredients"
              :key="ingredient.id"
              :label="ingredient.name"
              :value="ingredient.id"
            />
          </el-select>

          <!-- 显示已选择的食材 -->
          <div class="selected-ingredients-preview" style="margin-top: 10px">
            <h4 style="margin: 10px 0 5px 0; font-size: 14px">
              已选择食材 ({{ selectedIngredients.length }})
            </h4>
            <el-tag
              v-for="(ingredient, index) in selectedIngredients"
              :key="index"
              closable
              @close="
                selectedIngredientIds = selectedIngredientIds.filter(
                  (id) => id !== ingredient.id
                )
              "
              style="margin-right: 8px; margin-bottom: 8px"
            >
              {{ ingredient.name }}
            </el-tag>
          </div>
        </el-form-item>

        <!-- 编辑状态下的食材和口味操作按钮 -->
        <el-form-item v-if="currentDishId">
          <el-button type="primary" @click="openIngredientDialog">
            选择食材
          </el-button>
          <el-button
            type="success"
            @click="openFlavorDialog"
            style="margin-left: 10px"
          >
            设置口味
          </el-button>
        </el-form-item>

        <el-form-item v-if="!isViewMode">
          <el-button type="primary" @click="handleSubmit">
            {{ currentDishId ? '更新' : '添加' }}
          </el-button>
          <el-button @click="handleDrawerClose">取消</el-button>
        </el-form-item>

        <el-form-item v-if="isViewMode">
          <el-button @click="handleDrawerClose">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 详情弹窗 -->
    <el-dialog
      title="菜品详情"
      v-model="detailDialogVisible"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-descriptions column="1">
        <el-descriptions-item label="菜品ID">{{
          detailData.id
        }}</el-descriptions-item>
        <el-descriptions-item label="菜品名称">{{
          detailData.dishName
        }}</el-descriptions-item>
        <el-descriptions-item label="所属商家">{{
          detailData.merchant || '未知商家'
        }}</el-descriptions-item>
        <el-descriptions-item label="所属分类">{{
          formatCategory(detailData.dishCategoryId)
        }}</el-descriptions-item>
        <el-descriptions-item label="价格(元)">{{
          detailData.price
        }}</el-descriptions-item>
        <el-descriptions-item label="热量(卡路里)">{{
          detailData.calorie
        }}</el-descriptions-item>
        <el-descriptions-item label="评分">
          <span class="clickable-rating" @click="openRatingList(detailData.id)">
            {{ detailData.dishRating.toFixed(2) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="评价人数">{{
          detailData.ratingCount
        }}</el-descriptions-item>
        <el-descriptions-item label="菜品图片">
          <el-image
            v-if="detailData.image"
            :src="detailData.image"
            style="width: 100px; height: 100px"
            fit="cover"
            :alt="detailData.dishName"
          />
        </el-descriptions-item>
        <el-descriptions-item label="菜品描述">{{
          detailData.description
        }}</el-descriptions-item>

        <!-- 食材信息 -->
        <el-descriptions-item
          v-if="detailData.ingredients && detailData.ingredients.length"
          label="食材信息"
        >
          <el-table
            :data="detailData.ingredients"
            style="width: 100%; margin-bottom: 20px"
          >
            <el-table-column prop="name" label="食材名称" />
          </el-table>
        </el-descriptions-item>

        <!-- 口味信息 -->
        <el-descriptions-item
          v-if="detailData.flavor && detailData.flavor.length"
          label="口味信息"
        >
          <el-tag
            v-for="(flavor, index) in detailData.flavor"
            :key="index"
            style="margin-right: 8px; margin-bottom: 8px"
          >
            {{ flavor }}
          </el-tag>
        </el-descriptions-item>

        <!-- 商家位置 -->
        <el-descriptions-item v-if="detailData.location" label="商家位置">
          {{ detailData.location }}
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 食材选择弹窗（仅用于编辑） -->
    <el-dialog title="选择食材" v-model="ingredientDialogVisible" width="60%">
      <div class="ingredient-selector">
        <el-input
          v-model="ingredientSearchText"
          placeholder="搜索食材"
          style="margin-bottom: 16px"
          clearable
        />

        <el-table
          :data="ingredients"
          style="width: 100%"
          v-loading="ingredientLoading"
          empty-text="暂无食材数据"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="食材名称" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button
                size="small"
                @click="toggleIngredient(scope.row)"
                :type="
                  selectedIngredients.some((ing) => ing.id === scope.row.id)
                    ? 'success'
                    : 'default'
                "
              >
                {{
                  selectedIngredients.some((ing) => ing.id === scope.row.id)
                    ? '已选择'
                    : '选择'
                }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="selected-ingredients">
          <h4 style="margin: 16px 0 8px 0">
            已选择食材 ({{ selectedIngredients.length }})
          </h4>
          <el-tag
            v-for="(ingredient, index) in selectedIngredients"
            :key="index"
            closable
            @close="selectedIngredients.splice(index, 1)"
            style="margin-right: 8px; margin-bottom: 8px"
          >
            {{ ingredient.name }}
          </el-tag>
        </div>
      </div>

      <template #footer>
        <el-button @click="ingredientDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveIngredients">确定</el-button>
      </template>
    </el-dialog>

    <!-- 口味选择弹窗（仅用于编辑） -->
    <el-dialog title="设置口味" v-model="flavorDialogVisible" width="40%">
      <div class="flavor-selector">
        <div class="flavor-checkboxes">
          <el-checkbox-group v-model="selectedFlavors">
            <el-checkbox
              v-for="flavor in flavorOptions"
              :key="flavor.id"
              :label="flavor.id"
              style="margin-right: 15px; margin-bottom: 10px"
            >
              {{ flavor.name }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>

      <template #footer>
        <el-button @click="flavorDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveFlavors">确定</el-button>
      </template>
    </el-dialog>

    <!-- 评分列表弹窗组件 -->
    <DishRatingList
      v-model:visible="ratingDialogVisible"
      :dish-id="currentRatingDishId"
    />
  </div>
</template>

<style scoped lang="scss">
.dish-management {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    flex-wrap: wrap;
    gap: 12px;

    h1 {
      font-size: 1.5rem;
      color: #1a202c;
      margin: 0;
    }

    .header-actions {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 12px;
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 24px;
  }

  .form-hint {
    color: #666;
    font-size: 12px;
    margin-top: 5px;
  }

  .selected-merchant {
    color: #333;
    font-size: 12px;
    margin-top: 5px;
    font-style: italic;
  }

  .ingredient-selector {
    max-height: 500px;
    overflow-y: auto;
  }

  .flavor-selector {
    padding: 10px;
  }

  .flavor-checkboxes {
    display: flex;
    flex-wrap: wrap;
    padding: 10px 0;
  }

  .el-checkbox {
    margin-bottom: 10px;
  }

  // 评分点击样式
  .clickable-rating {
    color: #409eff;
    cursor: pointer;
    text-decoration: underline;
    &:hover {
      color: #66b1ff;
    }
  }
}
</style>
